#include "TaskModel.h"
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QStandardPaths>

TaskModel::TaskModel(QObject *parent)
    : QAbstractListModel(parent)
{
    m_roleNames[NameRole] = "name";
    m_roleNames[ExecuteCountRole] = "executeCount";
    m_roleNames[DayPointsRole] = "dayPoints";

    // 检查数据文件是否存在并加载
    QFile file(getDataFilePath());
    if (file.exists()) {
        if (!loadFromJsonFile()) {
            qWarning() << "Failed to load task data from file, initializing with empty task list";
            createInitialJsonFile();
        }
    } else {
        // 文件不存在，创建初始文件
        createInitialJsonFile();
    }
}

int TaskModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return m_taskList.size();
}

QVariant TaskModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() < 0 || index.row() >= m_taskList.size())
        return QVariant();

    const Task &task = m_taskList.at(index.row());

    switch (role) {
    case NameRole:
        return task.name;
    case ExecuteCountRole:
        return task.executeCount;
    case DayPointsRole:
        return QVariant::fromValue(getDayPoints(index.row()));
    default:
        return QVariant();
    }
}

bool TaskModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || index.row() < 0 || index.row() >= m_taskList.size())
        return false;

    Task &task = m_taskList[index.row()];
    bool changed = false;

    switch (role) {
    case NameRole:
        if (task.name != value.toString()) {
            task.name = value.toString();
            changed = true;
        }
        break;
    case ExecuteCountRole:
        if (task.executeCount != value.toInt()) {
            task.executeCount = value.toInt();
            changed = true;
        }
        break;
    }

    if (changed) {
        emit dataChanged(index, index, {role});
        saveTaskData(); // 保存到文件
        return true;
    }

    return false;
}

Qt::ItemFlags TaskModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    return Qt::ItemIsEditable | QAbstractListModel::flags(index);
}

QHash<int, QByteArray> TaskModel::roleNames() const
{
    return m_roleNames;
}

void TaskModel::addTask(const QString& name, int executeCount, const QVariantList &points)
{
    // 将QVariantList转换为int数组
    int pointArray[7] = {0};
    for(int i = 0; i < 7 && i < points.size(); ++i) {
        pointArray[i] = points[i].toInt();
    }

    beginInsertRows(QModelIndex(), m_taskList.size(), m_taskList.size());
    m_taskList.append(Task(name, executeCount, pointArray));
    endInsertRows();
    saveTaskData(); // 保存到文件
}

void TaskModel::removeTask(int index)
{
    if (index < 0 || index >= m_taskList.size())
        return;

    beginRemoveRows(QModelIndex(), index, index);
    m_taskList.removeAt(index);
    endRemoveRows();
    saveTaskData(); // 保存到文件
}

void TaskModel::updateTask(int index, const QString& name, int executeCount)
{
    if (index < 0 || index >= m_taskList.size())
        return;

    Task &task = m_taskList[index];
    task.name = name;
    task.executeCount = executeCount;

    QModelIndex modelIndex = createIndex(index, 0);
    emit dataChanged(modelIndex, modelIndex, {NameRole, ExecuteCountRole});
    saveTaskData(); // 保存到文件
}

void TaskModel::updateDayPoints(int taskIndex, int dayIndex, int points)
{
    if (taskIndex < 0 || taskIndex >= m_taskList.size() || dayIndex < 0 || dayIndex >= 7)
        return;

    Task &task = m_taskList[taskIndex];
    task.dailyPoints[dayIndex] = points;

    QModelIndex modelIndex = createIndex(taskIndex, 0);
    emit dataChanged(modelIndex, modelIndex, {DayPointsRole});
    saveTaskData(); // 保存到文件
}

QVariantList TaskModel::getDayPoints(int taskIndex) const
{
    QVariantList pointsList;

    if (taskIndex < 0 || taskIndex >= m_taskList.size())
        return pointsList;

    const Task &task = m_taskList.at(taskIndex);
    for (int i = 0; i < 7; ++i) {
        pointsList.append(task.dailyPoints[i]);
    }

    return pointsList;
}

void TaskModel::clearAll()
{
    if (m_taskList.isEmpty())
        return;

    beginRemoveRows(QModelIndex(), 0, m_taskList.size() - 1);
    m_taskList.clear();
    endRemoveRows();
    saveTaskData(); // 保存到文件
}

void TaskModel::completeTask(int taskIndex, int dayIndex)
{
    if (taskIndex < 0 || taskIndex >= m_taskList.size() || dayIndex < 0 || dayIndex >= 7)
        return;

    Task &task = m_taskList[taskIndex];
    if (task.dailyStatus[dayIndex] == 0) { // 只有未完成时才处理
        task.dailyStatus[dayIndex] = 1;

        // 发出数据变化信号，更新UI
        QModelIndex modelIndex = createIndex(taskIndex, 0);
        emit dataChanged(modelIndex, modelIndex, {DayPointsRole});
        saveTaskData();

        qDebug() << "Task" << task.name << "day" << dayIndex << "completed, points:" << task.dailyPoints[dayIndex];
    }
}

// 新增：JSON存储相关方法的实现
void TaskModel::saveTaskData()
{
    QJsonArray tasksArray;

    for (const Task &task : m_taskList) {
        tasksArray.append(task.toJson());
    }

    QJsonObject jsonObj;
    jsonObj["tasks"] = tasksArray;
    jsonObj["version"] = "1.0";

    QJsonDocument doc(jsonObj);
    QFile file(getDataFilePath());

    if (file.open(QIODevice::WriteOnly)) {
        file.write(doc.toJson());
        file.close();
        qDebug() << "Task data saved successfully, task count:" << m_taskList.size();
    } else {
        qWarning() << "Failed to save task data:" << file.errorString();
    }
}

void TaskModel::loadTaskData()
{
    if (loadFromJsonFile()) {
        qDebug() << "Task data loaded successfully, task count:" << m_taskList.size();
    } else {
        qWarning() << "Failed to load task data";
    }
}

QString TaskModel::getDataFilePath() const
{
    // 使用应用程序数据目录
    QString dataDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dataDir);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    return dir.filePath("taskdata.json");
}

void TaskModel::createInitialJsonFile()
{
    QJsonArray tasksArray;

    // 可以添加一些示例任务，或者保持空数组
    // 示例：添加一个默认任务
    /*
    Task defaultTask("示例任务", 1);
    int defaultPoints[] = {5, 5, 10, 10, 15, 15, 20};
    for (int i = 0; i < 7; ++i) {
        defaultTask.dayPoints[i] = defaultPoints[i];
    }
    tasksArray.append(defaultTask.toJson());
    */

    QJsonObject jsonObj;
    jsonObj["tasks"] = tasksArray;
    jsonObj["version"] = "1.0";

    QJsonDocument doc(jsonObj);
    QFile file(getDataFilePath());

    if (file.open(QIODevice::WriteOnly)) {
        file.write(doc.toJson());
        file.close();
        qDebug() << "Initial task data file created successfully";
    } else {
        qWarning() << "Failed to create initial task data file:" << file.errorString();
    }
}

bool TaskModel::loadFromJsonFile()
{
    QFile file(getDataFilePath());
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to open task data file for reading:" << file.errorString();
        return false;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull() || !doc.isObject()) {
        qWarning() << "Invalid JSON format in task data file";
        return false;
    }

    QJsonObject jsonObj = doc.object();
    QJsonArray tasksArray = jsonObj["tasks"].toArray();

    // 清空当前任务列表
    if (!m_taskList.isEmpty()) {
        beginRemoveRows(QModelIndex(), 0, m_taskList.size() - 1);
        m_taskList.clear();
        endRemoveRows();
    }

    // 从JSON数组加载任务
    if (!tasksArray.isEmpty()) {
        beginInsertRows(QModelIndex(), 0, tasksArray.size() - 1);
        for (const QJsonValue &taskValue : tasksArray) {
            QJsonObject taskObj = taskValue.toObject();
            m_taskList.append(Task(taskObj));
        }
        endInsertRows();
    }

    return true;
}
